"""
网络请求工具模块
"""
from typing import Tuple, Optional
import requests
from config import config
from logger import logger


def fetch_real_url(url: str, headers: Optional[dict] = None) -> str:
    """
    获取重定向后的真实 URL

    Args:
        url: 原始 URL
        headers: 自定义请求头

    Returns:
        重定向后的真实 URL
    """
    try:
        request_headers = headers or config.DEFAULT_HEADERS
        response = requests.get(
            url,
            headers=request_headers,
            timeout=config.REQUEST_TIMEOUT,
            allow_redirects=True,
            verify=config.REQUEST_VERIFY_SSL
        )
        return response.url
    except requests.RequestException as e:
        logger.error(f"获取真实URL失败: {e}")
        return url


def fetch_page_content(url: str, headers: Optional[dict] = None) -> Tuple[str, str]:
    """
    获取页面真实 URL 和 HTML 内容

    Args:
        url: 目标 URL
        headers: 自定义请求头

    Returns:
        (真实URL, HTML内容) 元组
    """
    try:
        request_headers = headers or config.DEFAULT_HEADERS
        response = requests.get(
            url,
            headers=request_headers,
            timeout=config.REQUEST_TIMEOUT,
            allow_redirects=True,
            verify=config.REQUEST_VERIFY_SSL
        )
        response.raise_for_status()
        return response.url, response.text
    except requests.RequestException as e:
        logger.error(f"获取页面内容失败: {e}")
        return url, ""


# 向后兼容的函数名
def fetch_real_url_playwright(url: str) -> str:
    """向后兼容函数名"""
    return fetch_real_url(url)


def fetch_page_with_playwright(url: str) -> Tuple[str, str]:
    """向后兼容函数名"""
    return fetch_page_content(url)
